package com.remoter.configure.json;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.util.Final;
import com.remoter.basic.util.ServiceLoader.MetaName;
import com.remoter.basic.util.StringUtil;

/**
 * @author			koko
 * @date 			2017-08-09 15:21:50
 * @description 	类功能说明
 */
@MetaName("json")
public class JsonConfiguration extends AbstractConfiguration{

	private static final JSONObject jsonObject = new JSONObject();
	
	public JsonConfiguration(){
		String path = this.getConfigFile();
		try(
			InputStream inputStream = this.getClass().getResourceAsStream(path);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		){
			if(null == inputStream){
				logger.warn("config file not found :" + path);
			}else{
				String json = null;
				byte[] buffer = new byte[1024];
		        int len = 0;
		        while((len = inputStream.read(buffer,0,buffer.length)) != -1){
		        	outputStream.write(buffer,0,len);
		        }
		        json = new String(outputStream.toByteArray(),Final.D_VAL_CHARSET);
		        jsonObject.putAll(JSON.parseObject(json));
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		if(logger.isDebugEnabled()){
			for(Entry<String,Object> entry : jsonObject.entrySet()){
				logger.debug(String.format("load config [%s=%s]",entry.getKey(),entry.getValue()));
			}
		}
	}
	
	@Override
	protected String getValue(String name) {
		if(StringUtil.isBlank(name)){
			return null;
		}
		String result = null;
		String[] names = null;
		if(name.indexOf(".")>0){
			names = name.split("\\.");
		}else{
			names = new String[]{name};
		}
		if(null != names && names.length > 0){
			JSONObject temp = jsonObject;
			for(int i=0;i<names.length;i++){
				String n = names[i];
				if(i == names.length - 1){
					result = temp.getString(n);
				}else{
					if(!temp.containsKey(n)){
						break;
					}
					temp = temp.getJSONObject(n);
				}
			}
		}
		return result;
	}
	
}